"""
支付相关API
"""
import json
from datetime import datetime, timedelta
from fastapi import APIRouter, Depends, HTTPException, status, Request, Form
from sqlalchemy.orm import Session, joinedload
from typing import Optional
from loguru import logger

from utils.database import get_db
from utils import JWTUtils
from utils.config import config
from utils.comm import get_ali_object
from utils.payment_utils import PaymentUtils, distributed_lock
from Models.travel.models import Order
from Models.travel.payment_models import Payment, Refund, PaymentStatus, PaymentMethod, RefundStatus
from Models.travel.payment_schemas import (
    PaymentInfo, PaymentCreate, PaymentResponse,
    RefundInfo, RefundCreate, RefundResponse
)
from Views.home.websocket.ws_notifier import (
    notify_payment_success,
    notify_payment_failed,
    notify_order_status_change
)

router = APIRouter(prefix="/payment", tags=["支付管理"])


def get_current_user_id(request: Request) -> int:
    """从请求头获取当前用户ID"""
    authorization = request.headers.get("Authorization")
    if not authorization:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="未提供认证令牌"
        )
    
    token = authorization.replace("Bearer ", "").strip()
    payload = JWTUtils.decode_access_token(token)
    if not payload or not payload.get("user_id"):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="认证令牌无效"
        )
    return payload["user_id"]


@router.post("/create", response_model=PaymentResponse, summary="创建支付")
async def create_payment(
    payment_data: PaymentCreate,
    request: Request,
    db: Session = Depends(get_db)
):
    """创建支付订单"""
    user_id = get_current_user_id(request)
    
    try:
        # 查询订单（预加载关联关系）
        order = db.query(Order).options(
            joinedload(Order.attraction)
        ).filter(
            Order.id == payment_data.order_id,
            Order.user_id == user_id
        ).first()
        
        if not order:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="订单不存在"
            )
        
        if order.status != "pending":
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"订单状态为 {order.status}，无法支付"
            )
        
        # 验证订单金额
        if order.total_amount <= 0:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"订单金额无效（{order.total_amount}），无法创建支付。订单金额必须大于0。"
            )
        
        # 检查是否已有支付记录
        existing_payment = db.query(Payment).filter(
            Payment.order_id == order.id,
            Payment.status.in_([PaymentStatus.PENDING, PaymentStatus.PROCESSING])
        ).first()
        
        if existing_payment:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="该订单已有进行中的支付记录"
            )
        
        # 生成支付流水号
        payment_no = PaymentUtils.generate_payment_no(order.order_no)
        
        # 创建支付记录
        payment = Payment(
            payment_no=payment_no,
            order_id=order.id,
            order_no=order.order_no,
            payment_method=payment_data.payment_method,
            amount=order.total_amount,
            status=PaymentStatus.PENDING,
            expired_at=datetime.now() + timedelta(minutes=15)  # 15分钟过期
        )
        
        db.add(payment)
        db.commit()
        db.refresh(payment)
        
        # 创建支付宝对象（这里会检查配置并输出警告）
        try:
            alipay = get_ali_object()
        except Exception as e:
            error_msg = f"初始化支付宝对象失败: {str(e)}"
            logger.error(error_msg, exc_info=True)
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="支付服务初始化失败，请检查配置"
            )
        
        # 验证回调地址配置
        from utils.config import config
        placeholder_keywords = ['your-public-url', 'your-ngrok-url', 'yourdomain.com', 'example.com']
        notify_has_placeholder = any(keyword in config.ALIPAY_NOTIFY_URL for keyword in placeholder_keywords)
        return_has_placeholder = any(keyword in config.ALIPAY_RETURN_URL for keyword in placeholder_keywords)
        
        if notify_has_placeholder or return_has_placeholder:
            error_detail = []
            if notify_has_placeholder:
                error_detail.append(f"notify_url包含占位符: {config.ALIPAY_NOTIFY_URL}")
            if return_has_placeholder:
                error_detail.append(f"return_url包含占位符: {config.ALIPAY_RETURN_URL}")
            
            error_msg = "支付宝回调地址未正确配置！\n\n"
            error_msg += "问题：" + "；".join(error_detail) + "\n\n"
            error_msg += "解决方案：\n"
            error_msg += "1. 启动ngrok转发到8000端口：ngrok http 8000\n"
            error_msg += "2. 在House(1)目录下创建.env文件，内容如下：\n"
            error_msg += "   ALIPAY_NOTIFY_URL=https://你的ngrok地址/api/payment/alipay/notify\n"
            error_msg += "   ALIPAY_RETURN_URL=https://你的ngrok地址/api/payment/alipay/return\n"
            error_msg += "3. 重启后端服务\n\n"
            error_msg += "详细说明请查看：House(1)/快速配置指南.md"
            
            logger.error(error_msg)
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=error_msg
            )
        
        # 生成支付的参数
        # 确保金额格式正确（保留两位小数）
        amount_str = f"{order.total_amount:.2f}"
        
        # 再次验证金额（防止浮点数精度问题）
        if float(amount_str) <= 0:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"订单金额无效（{amount_str}），无法创建支付。订单金额必须大于0。"
            )
        
        subject = f"订单支付-{order.order_no}"
        try:
            order_string = alipay.direct_pay(
            subject=subject,
            out_trade_no=order.order_no,
            total_amount=amount_str
        )
        except Exception as e:
            error_msg = f"生成支付参数失败: {str(e)}"
            logger.error(error_msg, exc_info=True)
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"生成支付参数失败: {str(e)}"
            )
        
        # 拼接最终的支付地址
        alipay_url = config.ALIPAY_URL + '?' + order_string
        
        # 更新支付记录
        payment.third_party_response = json.dumps({"alipay_url": alipay_url}, ensure_ascii=False)
        payment.status = PaymentStatus.PROCESSING
        db.commit()
        db.refresh(payment)
        
        response = PaymentResponse(
            payment_no=payment.payment_no,
            payment_url=alipay_url,
            order_no=order.order_no,
            amount=order.total_amount,
            expired_at=payment.expired_at,
            qr_code=None,  # 页面支付不需要二维码
            payment_type="page"  # 页面支付类型
        )
        
        logger.info(
            f"创建支付成功 - 订单号: {order.order_no}, "
            f"订单总金额: {order.total_amount}, "
            f"支付号: {payment.payment_no}"
        )
        
        return response
        
    except HTTPException:
        # 重新抛出HTTP异常（如订单不存在等）
        raise
    except Exception as e:
        # 改进错误信息提取，确保能获取到错误详情
        error_type = type(e).__name__
        error_msg = str(e) if str(e) else repr(e)
        error_detail = f"{error_type}: {error_msg}" if error_msg else f"{error_type} (无错误消息)"
        
        logger.error(f"创建支付失败: {error_detail}", exc_info=True)
        
        # 如果已创建支付记录，更新状态为失败
        if 'payment' in locals() and payment:
            try:
                payment.status = PaymentStatus.FAILED
                db.commit()
            except Exception:
                db.rollback()
        
        # 返回更友好的错误信息
        # 优先返回原始错误信息，特别是支付宝相关的错误
        if "支付宝" in error_detail or "alipay" in error_detail.lower():
            error_message = error_detail
        elif "未配置" in error_detail or "配置" in error_detail:
            error_message = "支付服务配置错误，请联系管理员"
        elif "ValueError" in error_type or "KeyError" in error_type:
            error_message = error_detail
        else:
            error_message = f"创建支付失败: {error_detail}"
        
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=error_message
        )


@router.post("/alipay/notify", summary="支付宝支付回调")
async def alipay_notify(
    request: Request,
    db: Session = Depends(get_db)
):
    """处理支付宝支付回调"""
    # 获取回调数据
    form_data = await request.form()
    notify_data = dict(form_data)
    
    logger.info(f"收到支付宝回调: {notify_data}")
    
    # 验证签名
    alipay = get_ali_object()
    signature = notify_data.pop('sign', None)
    if not signature:
        logger.warning("支付宝回调缺少签名")
        return {"code": "fail", "msg": "缺少签名"}
    
    if not alipay.verify(notify_data.copy(), signature):
        logger.warning("支付宝回调验签失败")
        return {"code": "fail", "msg": "验签失败"}
    
    # 获取订单号
    order_no = notify_data.get("out_trade_no")
    trade_no = notify_data.get("trade_no")
    # 支付宝回调可能没有 trade_status，需要从其他字段判断
    trade_status = notify_data.get("trade_status")
    if not trade_status:
        # 如果有 trade_no，说明支付成功
        if trade_no:
            trade_status = "TRADE_SUCCESS"
    
    if not order_no:
        logger.warning("支付宝回调缺少订单号")
        return {"code": "fail", "msg": "缺少订单号"}
    
    # 查询支付记录
    payment = db.query(Payment).filter(
        Payment.order_no == order_no
    ).order_by(Payment.created_at.desc()).first()
    
    if not payment:
        logger.warning(f"支付记录不存在: {order_no}")
        return {"code": "fail", "msg": "支付记录不存在"}
    
    # 使用分布式锁防止重复处理
    old_order_status = None
    try:
        with distributed_lock(f"payment_notify:{order_no}", timeout=30):
            # 重新查询（防止并发）
            payment = db.query(Payment).filter(Payment.id == payment.id).first()
            
            # 如果已经处理过，直接返回成功
            if payment.status == PaymentStatus.SUCCESS:
                logger.info(f"支付已处理: {order_no}")
                return {"code": "success"}
            
            # 更新支付记录
            payment.notify_data = json.dumps(notify_data, ensure_ascii=False)
            payment.notify_count += 1
            payment.last_notify_at = datetime.now()
            
            # 处理不同的交易状态
            if trade_status == "TRADE_SUCCESS" or trade_status == "TRADE_FINISHED":
                payment.status = PaymentStatus.SUCCESS
                payment.third_party_trade_no = trade_no
                payment.paid_at = datetime.now()
                
                # 更新订单状态（确保订单状态正确更新）
                order = db.query(Order).filter(Order.id == payment.order_id).first()
                if order:
                    old_order_status = order.status
                    # 无论订单当前状态如何，如果支付成功，都应该更新为已支付
                    if order.status == "pending":
                        order.status = "paid"
                        order.paid_at = datetime.now()
                        logger.info(f"订单状态已更新: {order_no}, pending -> paid")
                    elif order.status != "paid":
                        # 如果订单状态不是pending也不是paid，记录警告但更新状态
                        logger.warning(f"订单状态异常，强制更新为已支付: {order_no}, 当前状态: {order.status}")
                        order.status = "paid"
                        order.paid_at = datetime.now()
                
                db.commit()
                logger.info(f"支付成功: {order_no}, 订单号: {order_no}, 支付宝交易号: {trade_no}")
                success = True
            elif trade_status == "TRADE_CLOSED":
                payment.status = PaymentStatus.CLOSED
                db.commit()
                logger.info(f"支付关闭: {order_no}")
                success = True
            else:
                logger.warning(f"未知交易状态: {trade_status}")
                db.commit()
                success = False
    except Exception as e:
        logger.error(f"处理支付回调失败: {e}", exc_info=True)
        db.rollback()
        success = False
    
    if success:
        # 发送WebSocket通知
        payment = db.query(Payment).filter(Payment.order_no == order_no).first()
        if payment:
            order = db.query(Order).filter(Order.id == payment.order_id).first()
            if order:
                # 发送支付成功通知
                notify_payment_success(
                    user_id=order.user_id,
                    order_id=order.id,
                    order_no=order.order_no,
                    amount=payment.amount,
                    payment_method="alipay"
                )
                # 发送订单状态变化通知（从pending到paid）
                if old_order_status and old_order_status != "paid":
                    notify_order_status_change(
                        user_id=order.user_id,
                        order_id=order.id,
                        order_no=order.order_no,
                        old_status=old_order_status,
                        new_status="paid",
                        amount=payment.amount
                    )
    
    return {"code": "success" if success else "fail"}


@router.get("/alipay/return", summary="支付宝支付返回页面")
async def alipay_return(
    request: Request,
    db: Session = Depends(get_db)
):
    """
    处理支付宝支付完成后的页面跳转（GET请求）
    用户在支付完成后会跳转到这个页面
    """
    # 获取URL参数
    query_params = dict(request.query_params)
    
    logger.info(f"收到支付宝返回页面请求: {query_params}")
    
    # 验证签名
    alipay = get_ali_object()
    signature = query_params.pop('sign', None)
    if not signature:
        logger.warning("支付宝返回页面缺少签名")
        from fastapi.responses import RedirectResponse
        return RedirectResponse(
            url=f"{config.ALIPAY_RETURN_URL}?status=fail&msg=缺少签名",
            status_code=302
        )
    
    if not alipay.verify(query_params.copy(), signature):
        logger.warning("支付宝返回页面验签失败")
        # 返回错误页面或重定向到错误页面
        from fastapi.responses import RedirectResponse
        return RedirectResponse(
            url=f"{config.ALIPAY_RETURN_URL}?status=fail&msg=验签失败",
            status_code=302
        )
    
    # 获取订单号
    order_no = query_params.get("out_trade_no")
    trade_no = query_params.get("trade_no")
    # 支付宝返回页面可能没有 trade_status，需要从其他字段判断
    trade_status = query_params.get("trade_status")
    if not trade_status:
        # 如果有 trade_no，说明支付成功
        if trade_no:
            trade_status = "TRADE_SUCCESS"
    
    if not order_no:
        logger.warning("支付宝返回页面缺少订单号")
        from fastapi.responses import RedirectResponse
        return RedirectResponse(
            url=f"{config.ALIPAY_RETURN_URL}?status=fail&msg=缺少订单号",
            status_code=302
        )
    
    # 查询支付记录
    payment = db.query(Payment).filter(
        Payment.order_no == order_no
    ).order_by(Payment.created_at.desc()).first()
    
    if not payment:
        logger.warning(f"支付记录不存在: {order_no}")
        from fastapi.responses import RedirectResponse
        return RedirectResponse(
            url=f"{config.ALIPAY_RETURN_URL}?status=fail&order_no={order_no}",
            status_code=302
        )
    
    # 使用分布式锁防止重复处理
    old_order_status = None
    try:
        with distributed_lock(f"payment_return:{order_no}", timeout=30):
            # 重新查询（防止并发）
            payment = db.query(Payment).filter(Payment.id == payment.id).first()
            
            # 如果已经处理过，直接返回成功
            if payment.status == PaymentStatus.SUCCESS:
                logger.info(f"支付已处理: {order_no}")
                order = db.query(Order).filter(Order.id == payment.order_id).first()
                success = True
            else:
                # 更新支付记录（如果有 return_data 字段）
                if hasattr(payment, 'return_data'):
                    payment.return_data = json.dumps(query_params, ensure_ascii=False)
                
                # 处理不同的交易状态
                if trade_status == "TRADE_SUCCESS" or trade_status == "TRADE_FINISHED":
                    payment.status = PaymentStatus.SUCCESS
                    payment.third_party_trade_no = trade_no
                    payment.paid_at = datetime.now()
                    
                    # 更新订单状态（确保订单状态正确更新）
                    order = db.query(Order).filter(Order.id == payment.order_id).first()
                    old_order_status = None
                    if order:
                        old_order_status = order.status
                        # 无论订单当前状态如何，如果支付成功，都应该更新为已支付
                        if order.status == "pending":
                            order.status = "paid"
                            order.paid_at = datetime.now()
                            logger.info(f"订单状态已更新: {order_no}, pending -> paid")
                        elif order.status != "paid":
                            # 如果订单状态不是pending也不是paid，记录警告但更新状态
                            logger.warning(f"订单状态异常，强制更新为已支付: {order_no}, 当前状态: {order.status}")
                            order.status = "paid"
                            order.paid_at = datetime.now()
                    
                    db.commit()
                    logger.info(f"支付成功: {order_no}, 订单号: {order_no}, 支付宝交易号: {trade_no}")
                    success = True
                elif trade_status == "TRADE_CLOSED":
                    payment.status = PaymentStatus.CLOSED
                    db.commit()
                    logger.info(f"支付关闭: {order_no}")
                    success = False
                    order = None
                else:
                    logger.warning(f"未知交易状态: {trade_status}")
                    db.commit()
                    success = False
                    order = None
    except Exception as e:
        logger.error(f"处理支付返回失败: {e}", exc_info=True)
        db.rollback()
        success = False
        order = None
    
    if success and order:
        # 重新查询支付记录以获取金额
        payment = db.query(Payment).filter(Payment.order_no == order_no).first()
        
        # 发送WebSocket通知
        if payment:
            # 发送支付成功通知
            notify_payment_success(
                user_id=order.user_id,
                order_id=order.id,
                order_no=order.order_no,
                amount=payment.amount,
                payment_method="alipay"
            )
            # 发送订单状态变化通知（从pending到paid）
            if old_order_status and old_order_status != "paid":
                notify_order_status_change(
                    user_id=order.user_id,
                    order_id=order.id,
                    order_no=order.order_no,
                    old_status=old_order_status,
                    new_status="paid",
                    amount=payment.amount
                )
        
        # 重定向到成功页面
        from fastapi.responses import RedirectResponse
        return RedirectResponse(
            url=f"{config.ALIPAY_RETURN_URL}?status=success&order_no={order_no}&trade_no={trade_no}",
            status_code=302
        )
    else:
        # 重定向到失败页面
        from fastapi.responses import RedirectResponse
        return RedirectResponse(
            url=f"{config.ALIPAY_RETURN_URL}?status=fail&order_no={order_no}",
            status_code=302
        )


@router.get("/query/{payment_no}", response_model=PaymentInfo, summary="查询支付状态")
async def query_payment(
    payment_no: str,
    request: Request,
    db: Session = Depends(get_db)
):
    """查询支付状态"""
    user_id = get_current_user_id(request)
    
    payment = db.query(Payment).join(Order).filter(
        Payment.payment_no == payment_no,
        Order.user_id == user_id
    ).first()
    
    if not payment:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="支付记录不存在"
        )
    return PaymentInfo.model_validate(payment)


@router.post("/sync/{order_no}", summary="同步订单支付状态")
async def sync_order_payment_status(
    order_no: str,
    request: Request,
    db: Session = Depends(get_db)
):
    """
    通过订单号同步支付状态到订单
    用于支付完成后主动同步支付状态（检查支付记录状态并更新订单状态）
    """
    user_id = get_current_user_id(request)
    
    # 查询订单
    order = db.query(Order).filter(
        Order.order_no == order_no,
        Order.user_id == user_id
    ).first()
    
    if not order:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="订单不存在"
        )
    
    # 如果订单已经是已支付状态，直接返回
    if order.status == "paid":
        return {
            "code": "success",
            "message": "订单已支付",
            "order_status": order.status
        }
    
    # 查询支付记录
    payment = db.query(Payment).filter(
        Payment.order_no == order_no
    ).order_by(Payment.created_at.desc()).first()
    
    if not payment:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="支付记录不存在"
        )
    
    # 使用分布式锁防止并发更新
    try:
        with distributed_lock(f"sync_payment:{order_no}", timeout=10):
            # 重新查询（防止并发）
            order = db.query(Order).filter(Order.id == order.id).first()
            payment = db.query(Payment).filter(Payment.id == payment.id).first()
            
            # 如果支付已经是成功状态，但订单状态还是pending，更新订单状态
            if payment.status == PaymentStatus.SUCCESS and order.status == "pending":
                old_order_status = order.status
                order.status = "paid"
                order.paid_at = payment.paid_at or datetime.now()
                db.commit()
                db.refresh(order)
                logger.info(f"同步订单状态成功: {order_no}, 订单状态: {order.status}")
                
                # 发送WebSocket通知
                notify_payment_success(
                    user_id=order.user_id,
                    order_id=order.id,
                    order_no=order.order_no,
                    amount=payment.amount,
                    payment_method="alipay"
                )
                # 发送订单状态变化通知
                notify_order_status_change(
                    user_id=order.user_id,
                    order_id=order.id,
                    order_no=order.order_no,
                    old_status=old_order_status,
                    new_status="paid",
                    amount=payment.amount
                )
                
                return {
                    "code": "success",
                    "message": "订单状态已同步为已支付",
                    "order_status": order.status,
                    "payment_status": payment.status
                }
            elif payment.status == PaymentStatus.SUCCESS:
                return {
                    "code": "success",
                    "message": "订单已支付",
                    "order_status": order.status,
                    "payment_status": payment.status
                }
            else:
                return {
                    "code": "pending",
                    "message": "订单待支付",
                    "order_status": order.status,
                    "payment_status": payment.status
                }
    except Exception as e:
        logger.error(f"同步订单支付状态失败: {e}", exc_info=True)
        db.rollback()
        return {
            "code": "error",
            "message": f"同步失败: {str(e)}",
            "order_status": order.status,
            "payment_status": payment.status if payment else None
        }


@router.post("/refund", response_model=RefundResponse, summary="申请退款")
async def create_refund(
    refund_data: RefundCreate,
    request: Request,
    db: Session = Depends(get_db)
):
    """申请退款"""
    user_id = get_current_user_id(request)
    
    # 查询订单
    order = db.query(Order).filter(
        Order.id == refund_data.order_id,
        Order.user_id == user_id
    ).first()
    
    if not order:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="订单不存在"
        )
    
    if order.status != "paid":
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="只有已支付的订单才能申请退款"
        )
    
    # 查询支付记录
    payment = db.query(Payment).filter(
        Payment.order_id == order.id,
        Payment.status == PaymentStatus.SUCCESS
    ).first()
    
    if not payment:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="支付记录不存在"
        )
    
    # 确定退款金额
    refund_amount = refund_data.refund_amount or payment.amount
    
    if refund_amount > payment.amount:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="退款金额不能超过支付金额"
        )
    
    # 检查是否已有退款记录
    existing_refund = db.query(Refund).filter(
        Refund.order_id == order.id,
        Refund.status.in_([RefundStatus.PENDING, RefundStatus.PROCESSING])
    ).first()
    
    if existing_refund:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="该订单已有进行中的退款记录"
        )
    
    # 生成退款流水号
    refund_no = PaymentUtils.generate_refund_no(order.order_no)
    
    # 创建退款记录
    refund = Refund(
        refund_no=refund_no,
        payment_id=payment.id,
        order_id=order.id,
        order_no=order.order_no,
        refund_amount=refund_amount,
        refund_reason=refund_data.refund_reason,
        status=RefundStatus.PENDING
    )
    
    db.add(refund)
    db.commit()
    db.refresh(refund)
    
    # 调用支付宝申请退款
    # 注意：新的支付模块暂不支持退款接口，需要后续扩展
    try:
        # TODO: 实现退款接口
        # 暂时将退款状态设为处理中，需要手动处理或后续实现退款接口
        refund.status = RefundStatus.PROCESSING
        refund.third_party_response = json.dumps({
            "message": "退款功能待实现",
            "refund_no": refund.refund_no
        }, ensure_ascii=False)
        db.commit()
        db.refresh(refund)
        
        logger.warning(f"退款功能暂未实现，退款号: {refund.refund_no}")
        
        return RefundResponse(
            refund_no=refund.refund_no,
            order_no=order.order_no,
            refund_amount=refund.refund_amount,
            status=refund.status
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"申请退款失败: {e}", exc_info=True)
        # 更新退款状态为失败
        if 'refund' in locals() and refund:
            try:
                refund.status = RefundStatus.FAILED
                db.commit()
            except Exception:
                db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"申请退款失败: {str(e)}"
        )


@router.get("/refund/{refund_no}", response_model=RefundInfo, summary="查询退款状态")
async def query_refund(
    refund_no: str,
    request: Request,
    db: Session = Depends(get_db)
):
    """查询退款状态"""
    user_id = get_current_user_id(request)
    
    refund = db.query(Refund).join(Order).filter(
        Refund.refund_no == refund_no,
        Order.user_id == user_id
    ).first()
    
    if not refund:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="退款记录不存在"
        )
    return RefundInfo.model_validate(refund)

